package com.jacky.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理模式之：动态代理
 * 实现InvocationHandler接口
 * 在调用时使用Proxy.newProxyInstance(classLoader,interfaces,handler)
 * classLoader:指定当前目标对象使用的类加载器
 * interfaces:目标对象实现的接口类型列表
 * handler:事件处理，执行目标对象的方法时，会触发事件处理器的invoke()方法，把当前执行目标对象的方法作为method参数传入
 */
public class MyInvocationHandler implements InvocationHandler {
//    private MyInterface myInterface;
    private Object obj;

    public MyInvocationHandler() {
    }

    public MyInvocationHandler(Object obj) {
        this.obj = obj;
    }

    public Object getInstance(Object object,Class<?>[] interfaces){
        this.obj = object;
        final Class<?> Clazz = obj.getClass();
        return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),interfaces,this);
    }

//    public MyInvocationHandler(MyInterface myInterface) {
//        this.myInterface = myInterface;
//    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(proxy,method);
//        Object invoke = method.invoke(myInterface, args);
        final Object invoke = method.invoke(obj, args);
        after(proxy,method);
        return invoke;
    }

    private void after(Object proxy, Method method) {
        System.out.println(proxy.getClass()+":after:"+method.getName());
    }

    private void before(Object proxy, Method method) {
        System.out.println(proxy.getClass()+":before:"+method.getName());

    }

}
